using System.Web.UI;

namespace OpenWaves.Web.Controls
{
    public class ExpandoControl : Control, IAttributeAccessor
    {
        private IStateManager attributesState;

        private AttributeCollection attributes;
        public virtual AttributeCollection Attributes 
        { 
            get { return this.EnsureAttributesCollection(); }
        }

        public string GetAttribute(string key)
        {
            return this.Attributes[key];
        }

        public void SetAttribute(string key, string value)
        {
            this.Attributes[key] = value;
        }

        protected virtual void AddAttributesToRender(HtmlTextWriter writer)
        {
            this.Attributes.AddAttributes(writer);
        }

        protected override void TrackViewState()
        {
            base.TrackViewState();
        
            if (this.attributes != null)
                this.attributesState.TrackViewState();
        }

        protected override object SaveViewState()
        {
            return new Pair(base.SaveViewState(), this.attributesState != null ? this.attributesState.SaveViewState() : null);
        }

        private AttributeCollection EnsureAttributesCollection(bool trackViewState = false)
        {
            if (this.attributes == null)
            {
                var stateBag = new StateBag(true);
                this.attributes = new AttributeCollection(stateBag);
                this.attributesState = stateBag;
                if (this.IsTrackingViewState || trackViewState)
                    this.attributesState.TrackViewState();
            }
            return this.attributes;
        }

        protected override void LoadViewState(object savedState)
        {
            var myState = (Pair) savedState;

            base.LoadViewState(myState.First);

            if (myState.Second != null)
            {
                this.EnsureAttributesCollection(true);
                this.attributesState.LoadViewState(myState.Second);
            }
        }
    }
}